package com.zz.hhbl.utils

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.content.Context
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import com.zz.framework.core.utils.AppGlobals
import java.lang.reflect.InvocationTargetException

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/3/5 15:59.
 *
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
object BluetoothConnectionUtils {
    fun getConnectedBluetoothDevicesCount(bluetoothAdapter: BluetoothAdapter?): Int {
        // 检查蓝牙适配器是否可用
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled) {
            return 0
        }
        // 获取已配对的设备集合
         if (ActivityCompat.checkSelfPermission(AppGlobals.getApplication(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            return 0
        }
        val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        // 检查蓝牙适配器是否可用
        if (bluetoothAdapter == null ||!bluetoothAdapter.isEnabled) {
            return 0
        }
        val bluetoothManager = AppGlobals.getApplication().getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        var connectedCount = 0
        // 检查 A2DP 配置文件的连接设备
        val a2dpConnectedDevices = bluetoothManager.getConnectedDevices(BluetoothProfile.A2DP)
        connectedCount += a2dpConnectedDevices.size

        // 检查 HFP 配置文件的连接设备
        val hfpConnectedDevices = bluetoothManager.getConnectedDevices(BluetoothProfile.HEADSET)
        connectedCount += hfpConnectedDevices.size

        // 检查 PAN 配置文件的连接设备
//        val panConnectedDevices = bluetoothManager.getConnectedDevices(BluetoothProfile.PAN)
//        connectedCount += panConnectedDevices.size
        return connectedCount
    }
}

fun BluetoothAdapter?.getConnectedBluetoothDevicesCount() = BluetoothConnectionUtils.getConnectedBluetoothDevicesCount(this)